package com.gph.saviorframework.uitl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 枚举类转化器
 */
public class EnumConvertor {

    /**
     * 此函数是个专用的函数
     * @param clazz
     * @return
     */
    public static Map<String, String> enum2Map(Class clazz) {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        try {
            Method toName = clazz.getMethod("getName");
            Method toCode = clazz.getMethod("getCode");
            //得到enum的所有实例
            Object[] objs = clazz.getEnumConstants();
            for (Object obj : objs) {
                map.put((String)toCode.invoke(obj),(String)toName.invoke(obj));
            }
            return map;
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Map<String, String>> enum2ListMap(Class clazz) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        try {
            Method toName = clazz.getMethod("getName");
            Method toCode = clazz.getMethod("getCode");
            //得到enum的所有实例
            Object[] objs = clazz.getEnumConstants();
            for (Object obj : objs) {
                LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
                map.put("value",(String)toCode.invoke(obj));
                map.put("name",(String)toName.invoke(obj));
                list.add(map);
            }
            return list;
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


}
